package com.gimi.cloud.jimi.common.utils;

import java.text.DateFormat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;


public class CommonUtil {
	public static boolean isEmpty(Object obj){
		if(null==obj||"".equals(obj)){
			return true;
		}
		return false;
	}
	
	/**
	 * json字符串转化成List<Map<String,Object>>
	 * eg. "[{\"roleName\":\"超级管理员角色\",\"roleEnable\":1,\"companyName\":\"重庆市江北区汇金小额贷款有限公司\"}]"
	 * @param jsonStr
	 * @return
	 */
	public static List<Map<String,Object>> jsonToList(String jsonStr){
		JSONArray json = JSONArray.parseArray(jsonStr);
		List<Map<String,Object>> mapListJson = (List)json;  
		return mapListJson;
	}
	
	/**
	 * 生成随机编码
	 * 
	 * @param length
	 * @return
	 */
	public static String randomCode(int length) {// 传入的字符串的长度
		StringBuilder builder = new StringBuilder(length);
		for (int i = 0; i < length; i++) {

			int r = (int) (Math.random() * 3);
			int rn1 = (int) (48 + Math.random() * 10);
			int rn2 = (int) (65 + Math.random() * 26);
			int rn3 = (int) (97 + Math.random() * 26);

			switch (r) {
			case 0:
				builder.append((char) rn1);
				break;
			case 1:
				builder.append((char) rn2);
				break;
			case 2:
				builder.append((char) rn3);
				break;
			}
		}
		return builder.toString().toUpperCase();
	}
	
	/**
	 * 格式化金额数字
	 * @param money
	 * @return
	 */
	public static String toMoney(Object money,String split){
		String result = "";
		String text = money.toString();
		String rail = "";
		String fh = "";
		if(text.indexOf("-")>=0){
			fh = text.substring(0,text.indexOf("-")+1);
			text = text.substring(text.indexOf("-")+1);
		}
		if(text.indexOf(".")>=0){
			rail = text.substring(text.indexOf("."));
			text = text.substring(0,text.indexOf("."));
			for(int i=text.length()-1,j=0;i>=0;i--,j++){
				if(j!=0&&j%3==0){
					result = text.charAt(i)+split+result;
				}else{
					result = text.charAt(i)+result;
				}
			}
		}else{
			for(int i=text.length()-1,j=0;i>=0;i--,j++){
				if(j!=0&&j%3==0){
					result = text.charAt(i)+split+result;
				}else{
					result = text.charAt(i)+result;
				}
			}
		}
		return fh+result+rail;
	}
	
	/**
	 * 格式化日期
	 * @param date
	 * @param formate
	 * @return
	 */
	public static String toDate(Object date,String formate){
		if(isEmpty(date)){
			return "";
		}
		String result = date.toString();
		try{
			if(isEmpty(formate)){
				formate = "yyyy-MM-dd";
			}
			DateFormat df = new SimpleDateFormat(formate);
			return df.format(df.parse(result));
		}catch(Exception e){
			return result;
		}
	}
	
	public static Date stringToDate(String datestr, String formate) {
		if(isEmpty(datestr)){
			return null;
		}
		try{
			if(isEmpty(formate)){
				formate = "yyyy-MM-dd";
			}
			DateFormat df = new SimpleDateFormat(formate);
			return df.parse(datestr);
		}catch(Exception e){
			return null;
		}
	}
	
	/**
	 * 判断指定字符串是否是JSON类型
	 * @param str 待判断的字符串
	 * @return 判断结果
	 */
	public static boolean isJson(String str){
		try{
			if(StringUtils.isNotBlank(str)){
				JSON.parse(str);
				return true;
			}
		}catch(Exception e){}
		
		return false;
	}

	public static String bodyHandle(String body,HttpServletRequest request,String[] names){
		String pre = ",";
		if(body == null){
			body = "{}";
		}
		if(body.endsWith("}")){
			body = body.substring(0,body.length()-1);
			for (String name : names){
				if(body.equals("{")){
					pre = "";
				}else{
					pre = ",";
				}
				if(body.indexOf(name) ==-1){
					String value = StringUtil.isBlank(request.getHeader(name.toLowerCase())) ? null : request.getHeader(name.toLowerCase());
					body += pre+"\""+name+"\":\""+value+"\"";
				}
			}
			return body+"}";
		}
		return body;
	}

	//校验是否是图片
	public static boolean checkImg(String imgUrl) {
		if(StringUtils.isNotBlank(imgUrl)) {
			String reg="(png|PNG|GIF|gif|jpg|JPG|pdf|PDF)";
			String[] url = null;
			if(imgUrl.indexOf(".") != -1) {
				url = imgUrl.split("\\.");
				if(url[url.length-1].matches(reg)) {
					return true;
				}
			}
		}
		return false;
	}

	//过滤它特殊字符
	public static String checkParams(String str) {
		if(!StringUtil.isBlank(str)){
			str = str.replaceAll("[\\s`~!@#$%^&*()+=|{}\"\':;,\\[\\].<>/?~！@#￥%……&*（）【】‘；：”“’。，、？]", "");
		}
		return str;
	}

	public static boolean checkIsImage(String imgType){
		if(StringUtil.isBlank(imgType)){
			throw new MsgException(ResponseCodeEnum.INVALID,"文件类型不能为空");
		}

		if(!imgType.equalsIgnoreCase("png")&&!imgType.equalsIgnoreCase("jpg")
				&&!imgType.equalsIgnoreCase("jpeg")){
			throw new MsgException(ResponseCodeEnum.INVALID,"不支持的文件类型" + imgType);
		}
		return true;
	}

}
